<!--
@description ： 创建自动加好友任务
-->

<template>
  <div v-loading="pageLoading">
    <div class="header-btn">
      <div>{{ $route.query.flag == '1' ? '新增任务' : '复用任务' }}</div>
      <div>
        <el-button type="primary" @click="addTask">确认</el-button>
        <el-button plain type="info" @click="goBack">返回</el-button>
      </div>
    </div>
    <div class="g-card">
      <el-form ref="form" :model="form" :rules="rules" label-suffix=":" label-width="140px"
               size="medium" style="padding-top: 26px">
        <el-form-item label="任务名称" prop="batchName">
          <el-input v-model.trim="form.batchName" clearable placeholder="不允许重复" style="width: 600px"/>
        </el-form-item>
        <el-form-item prop="automateId">
          <template slot="label">
            <span class="before-hasValue">超级企微:</span>
          </template>
          <select-supermicro ref="checkDigitalEmployee" v-model="form.automateId"
                             :is-single-option="isSingleOption"></select-supermicro>
        </el-form-item>
        <el-form-item prop="ocLeadNo">
          <template slot="label">
            <span class="before-hasValue">拓客线索:</span>
          </template>
          <check-number-base ref="checkNumberBase" v-model="form.ocLeadNo" :btn-info.sync="btnInfo"
                             :query-oc-lead-type.sync="queryOcLeadType"></check-number-base>
        </el-form-item>
        <el-form-item label="任务开始时间" prop="batchType" required>
          <el-radio-group v-model="form.batchType" @change="form.batchType == '0' ? form.batchTime = '' : ''">
            <el-radio label="0">立即发送</el-radio>
            <el-radio label="1">定时发送</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.batchType == 1" label="发送时间" prop="batchTime">
          <el-date-picker v-model="form.batchTime" placeholder="选择日期时间" style="width: 600px"
                          type="datetime" value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="每天加人时间" prop="addTime">
          <el-time-picker
            v-model="form.addTime[0]"
            placeholder="开始时间"
            style="width: 284px"
            value-format="HH:mm:ss">
          </el-time-picker>
          <span style="width:32px;display: inline-block;text-align: center;font-size: 18px">至</span>
          <el-time-picker
            v-model="form.addTime[1]"
            placeholder="结束时间"
            style="width: 284px"
            value-format="HH:mm:ss">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="加人间隔" prop="addInterval" required>
          <el-slider
            v-model="form.addInterval"
            :max="150"
            :min="1"
            range
            style="width: 600px">
          </el-slider>
        </el-form-item>
        <div style="margin-bottom: 6px">
            <span
              style="margin-left: 140px;color: #ccc">每隔[{{ form.addInterval[0] }}]~[{{
                form.addInterval[1]
              }}]分钟发送一次请求</span>
        </div>
        <el-form-item label="请求人数上限" prop="upperLimit">
          <span
            style="font-size: 14px;">每24小时</span>
          <el-input-number v-model="form.upperLimit" :max="50" :min="1" :precision="0" :step="1" label="描述文字"/>
          <span
            style="font-size: 14px;">人</span>
        </el-form-item>
        <el-form-item label="验证语" prop="verificationType">
          <el-switch v-model="form.verificationType" active-color="#082aff" inactive-color="#DCDFE6"/>
        </el-form-item>
        <el-form-item v-if="form.verificationType" label="" prop="verificationContent">
          <el-input v-model="form.verificationContent" :autosize="{ minRows: 3 }" maxlength="50"
                    placeholder="请输入验证语"
                    show-word-limit style="width: 800px;margin-bottom: 12px" type="textarea">
          </el-input>
        </el-form-item>
        <el-form-item label="打标签">
          <el-switch v-model="form.tagType" active-color="#082aff" inactive-color="#DCDFE6"/>
        </el-form-item>
        <el-form-item v-if="form.tagType" label="" prop="label">
          <tag-group v-model="form.customerTag"/>
        </el-form-item>
        <el-form-item label="打备注">
          <el-switch v-model="form.remarkType" active-color="#082aff" inactive-color="#DCDFE6"/>
        </el-form-item>
        <el-form-item v-if="form.remarkType" label="" prop="remark">
          <el-input v-model="form.remark" :rows="4" maxlength="100" placeholder="请输入备注内容" show-word-limit
                    style="width: 800px;"
                    type="textarea">
          </el-input>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import selectSupermicro from "@/components/selectSupermicro.vue";
import checkNumberBase from "@/components/checkNumberBase.vue";
import tagGroup from "@/components/tagGroup.vue";
import NormalSelectMaterial from "@/components/NormalSelectMaterial.vue";
import moment from "moment";
import {addAutomate, getAutomateDetail} from "@/api/beathAddAuto";

export default {
  name: "addBeathAutoTask", //创建加好友任务
  props: {},
  components: {
    checkNumberBase,
    tagGroup,
    NormalSelectMaterial,
    selectSupermicro
  },
  data() {
    const checkAddTime = (rule, value, callback) => {
      if (value) {
        if (!value[0] || !value[1]) {
          return callback(new Error('请选择每天加人时间'))
        } else {
          let today = new Date();
          let date1 = new Date(today.toDateString() + " " + value[0])
          let date2 = new Date(today.toDateString() + " " + value[1])
          if (date1 > date2) {
            return callback(new Error('开始时间不能大于结束时间'))
          } else {
            callback()
          }
        }
      } else {
        return callback(new Error('请选择每天加人时间'))
      }
    };
    return {
      form: {
        batchName: '',
        automateId: [],
        ocLeadNo: [],
        batchType: '0',
        addTime: [],
        addInterval: [5, 60],
        batchTime: '',
        upperLimit: 0,
        verificationType: false,
        // verificationContent: [''],
        verificationContent: '',
        tagType: false,
        customerTag: [],
        remarkType: false,
        remark: '',
      },
      isSingleOption: false,
      btnInfo: '选择',
      rules: {
        batchName: [
          {required: true, message: '请输入任务名称', trigger: 'blur'}
        ],
        addTime: [{required: true, message: '请选择每天加人时间', trigger: ['change', 'blur']},{validator: checkAddTime, trigger: ['change', 'blur']}],
        upperLimit: [
          {required: true, message: '请输入请求人数上限', trigger: 'blur'}
        ],
        batchTime: [
          {required: true, message: '请选择发送时间', trigger: ['change', 'blur']},
        ],
      },
      pageLoading: false,
      queryOcLeadType: '2',
    }
  },
  methods: {
    addTask() {
      if (this.form.addTime) {
        if (!this.form.addTime[0] || !this.form.addTime[1]) return this.$message.error('请选择每天加人时间')
        let today = new Date();
        let date1 = new Date(today.toDateString() + " " + this.form.addTime[0]);
        let date2 = new Date(today.toDateString() + " " + this.form.addTime[1]);
        console.log(date1, date2, this.form.addTime, 'addTime')
        if (date1 > date2) {
          return this.$message.error('开始时间不能大于结束时间')
        }
      }
      // const addTimeArr = JSON.parse(JSON.stringify(this.form.addTime))
      const addTimeArr = this.form.addTime
      const addTimeStr = moment(addTimeArr[0], 'HH:mm:ss').format('HH:mm:ss') + ',' + moment(addTimeArr[1], 'HH:mm:ss').format('HH:mm:ss')
      console.log(this.form.addTime, addTimeArr, addTimeStr, 'form')
      if (this.form.automateId.length == 0) return this.$message.error('请选择超级企微')
      if (this.form.ocLeadNo.length == 0) return this.$message.error('请选择拓客线索')
      if (this.form.verificationType && !this.form.verificationContent) return this.$message.error('请输入验证语内容')
      if (this.form.tagType && this.form.customerTag.length == 0) return this.$message.error('请打标签')
      if (this.form.remarkType && !this.form.remark) return this.$message.error('请输入备注')
      this.$refs['form'].validate((valid) => {
        console.log('valid', valid);
        if (valid) {
          let obj = {
            ...this.form,
            verificationType: this.form.verificationType ? '0' : '1',
            tagType: this.form.tagType ? '0' : '1',
            remarkType: this.form.remarkType ? '0' : '1',
            ocLeadNo: this.form.ocLeadNo?.[0]?.ocLeadNo,
            automateId: this.form.automateId?.[0]?.automateId,
            addTime: addTimeStr,
            addInterval: JSON.stringify(this.form.addInterval),
            customerTag: this.form.tagType && this.form.customerTag.length > 0 ? JSON.stringify(this.form.customerTag) : ''
          }
          this.pageLoading = true
          addAutomate(obj).then(res => {
            if (res.code == 200) {
              this.$message.success('新增成功')
              this.pageLoading = false
              this.$router.push({
                name: 'Beath',
                query: {
                  activeName: '2'
                }
              })
            }
          }).catch(() => {
            this.pageLoading = false
          })
        } else {
          this.$message.error('信息还未录入完成，请核对后提交！')
        }
      })
    },
    goBack() {
      this.$router.push({
        name: 'Beath',
        query: {
          activeName: '2'
        }
      })
    },
    confirmSelectFn(val) {
      this.form.welcomeMsg = val;
    },
  },
  mounted() {
    if (this.$route.query.flag == '2' && this.$route.query.batchId) {
      this.pageLoading = true
      getAutomateDetail({batchId: this.$route.query.batchId}).then(res => {
        if (res.code == 200) {
          let addTime = []
          if (res.data.addTime) {
            const addTimeArr = res.data.addTime.split(',')
            addTime = addTimeArr
          }
          console.log(res.data.addTime, addTime, 'addTime')
          let obj = {
            ...res.data,
            verificationType: res.data.verificationType == '0' ? true : false,
            tagType: res.data.tagType == '0' ? true : false,
            remarkType: res.data.remarkType == '0' ? true : false,
            automateId: res.data.automateId ? [{
              userName: res.data?.userName,
              automateId: res.data?.automateId,
              id: res.data?.automateId
            }] : [],
            ocLeadNo: res.data.ocLeadNo ? [{ocLeadNo: res.data.ocLeadNo, ocLeadName: res.data.ocLeadName}] : [],
            addInterval: res.data.addInterval ? JSON.parse(res.data?.addInterval) : '',
            customerTag: res.data.customerTag ? JSON.parse(res.data.customerTag) : [],
            batchType: String(res.data.batchType),
            addTime: addTime
          }
          this.form = obj
          this.$set(this, 'form', obj)
          console.log(this.form, 'form', '123')
        }
        this.pageLoading = false
      }).catch(() => {
        this.pageLoading = false
      })
    }
  },
  created() {
  },
}

</script>

<style lang="scss" scoped>
@import '@/styles/base.scss';

.header-btn {
  @include headerBtn;
}

::v-deep.el-form-item {
  padding: 10px 4px;
}

.conIcon {
  font-size: 32px;
  cursor: pointer;
  color: #082aff;
}


.before-hasValue::before {
  content: "*";
  color: #e74e59;
  margin-right: 4px;
}

::v-deep {
  .el-textarea .el-input__count {
    right: -46px;
    bottom: -5px;
  }
}
</style>
